// index.js
var app = getApp();
const utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // showType = 1
    Word: '',//关键词
    CurrentPage: 1,
    Categorys: [],
    selCatId: 0,
    selCatName: '',
    Brands: [],
    selBrandId: 0,
    selBrandName: '',
    Prices: [],
    selPriceId: 0,
    selPriceName: '',
    isCategoryTap: false,
    isBrandTap: false,
    isPriceTap: false,
    showSearch: false,
    searchCategory: [],//当前搜索类型
    goodsResult: [],
    loadingMoreHidden: true,
    storeId: 0,
    pageSize: 8,
    searchbg: "",
    cardInfo:{},
    typeList:[],
    isopenred:false,
    showType:1,
    //showType = 2
    selectedMenuId: 0,
    categoriesTwo: [],
    classLogo: "",
    classProduct: [],
    showProduct: true,
    imgsrc: "",
    logoclassOne: "",
    selectid: 0,
    selectname: "",
    productArr: [],
    searchbg: ""
  },

  /**
    * 产品分类显示方式
    * value = 1 淘宝方式
    * value = 2 京东方式
    */
  getClassProductType: function () {
    var that = this;
    var staffid = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + '/api/staff/GetProductView?staffid=' + staffid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Value == 2) {
            that.setData({ showType: 2 });
            that.getClassTwoData();
          }else{
            that.setData({ showType: 1 });
            that.getClassData();
          }
        }else{
          that.setData({ showType: 1 });
          that.getClassData();
        }
      }
    })
  },

  //用户可领取的优惠券
  GetCouponTypeList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetSendingCouponTypeList',
      data: {
        storeid: app.globalData.storeId,
        uid:app.globalData.userInfo.Uid
      },
      success: function (res) { 
        if (res.data.Code == 0) {
          var couPonList = res.data.Data
          for (var i = 0; i < couPonList.length; i++) {
            couPonList[i].UseStartTime = couPonList[i].SendStartTime.slice(0, 10)
            couPonList[i].UseEndTime = couPonList[i].SendEndTime.slice(0, 10)
          }
          that.setData({
            typeList: res.data.Data
          })
        }
      }
    })
  },

  /**
 * 领取优惠券
 */
  getOpenRed: function (e) {
    var that = this;
    that.setData({ isopenred: true })
    var typeList = that.data.typeList;
    wx.request({
      url: app.globalData.host + '/api/coupon/GetCoupon',
      data: {
        couponTypeId: typeList[0].CouponTypeId,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({ isopenred: true })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  //使用优惠券
  couponUse:function(){
    this.setData({ typeList: [], isopenred:false})
  },

  //关闭弹框
  closeRed:function(){
    var that = this;
    var closetimes = wx.getStorageSync("closetimes");
    wx.showModal({
      title: '提示',
      content: '是否放弃领取优惠',
      success: function (res) {
        if (res.confirm) {
          if (!closetimes) {
            closetimes = 0;
          }
          closetimes++;
          wx.setStorageSync("closetimes", closetimes);
          that.setData({ typeList: [], isopenred: false })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 获取名片信息
  getAiCardInfo: function () {
    var that = this;
    var cardId = wx.getStorageSync("cardId")
    if (cardId) {
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/GetAiCard?uid=' + app.globalData.userInfo.Uid + '&staffId=' + cardId,
        success: function (res) {
          if (res.data.Code == 0) {
            var cardInfo = res.data.Data;
            var urlImg = "https://static.711688.net.cn/upload/card/source/thumb600_600/";
            cardInfo.CardInfo.Avater = utils.formatAvater(cardInfo.CardInfo.Avater, urlImg);
            that.setData({
              cardInfo: cardInfo
            })
          }
        },
      })
    }
  },
  
  toDetailsTap: function (e) {
    var that = this
    var pid = e.currentTarget.dataset.id
    //获取拼团信息
    wx: wx.request({
      url: app.globalData.host + '/api/Store/GetGroupBuyProductInfo?storeId=' + app.globalData.storeId + '&pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {
          wx.navigateTo({
            url: '/pages/pintuan-details/index?id=' + pid,
          })
        } else {
          wx.navigateTo({
            url: "/pages/goods-details/index?id=" + pid
          })
        }
      }
    })
  },
  onShow: function () {
    var that = this;
    var closetimes = wx.getStorageSync("closetimes")
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      if (closetimes != 2){ //手动关闭超过两次取消弹出
        that.GetCouponTypeList();
      }
      that.getAiCardInfo();
      utils.aiCardActionRecord(0);
      that.updateSource();
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  //修改客户来源
  updateSource: function () {
    var cardId = wx.getStorageSync("cardId")
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/UpdateSource?staffId=' + cardId + '&uid=' + app.globalData.userInfo.Uid + '&source=2',
      success: function (res) {},
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (options.source == 2) {
      if (options.cardid) {
        wx.setStorageSync("cardId", options.cardid)
      }
    }
    that.setData({
      storeId: app.globalData.storeId,
    })
    that.getClassProductType();
  },


  getClassData:function(){
    var that = this;
    var prices = [{ id: 0, name: '不限制' }, { id: 1, name: '0-100' }, { id: 2, name: '100-300' }, { id: 3, name: '300-600' }, { id: 4, name: '600-1000' }, { id: 5, name: '1000-2000' }];
    that.data.Prices = prices;
    wx.request({
      url: app.globalData.host + '/api/store/GetStoreClassList',
      data: {
        storeId: app.globalData.storeId
      },
      success: function (res) {
        var categories = [{ id: 0, name: "不限制", parentid: 0 }];
        for (var i = 0; i < res.data.Data.length; i++) {
          var temp = res.data.Data[i];
          var c = {};
          c.parentid = temp.ParentId
          c.id = temp.StoreCid;
          c.name = temp.Name;
          categories.push(c);
        }
          var selCatName = ""
          var selCatId = 0
        that.setData({
          Categorys: categories,
          selCatName: selCatName,
          selCatId: selCatId
        });
        that.searchGoods();
      }
    })
  },

  searchGoods: function () {
    var that = this;
    var priceStart = 0;
    var priceEnd = 0;
    if (that.data.selPriceId == 1) { priceStart = 0; priceEnd = 100; }
    else if (that.data.selPriceId == 2) { priceStart = 100; priceEnd = 300 }
    else if (that.data.selPriceId == 3) { priceStart = 300; priceEnd = 600 }
    else if (that.data.selPriceId == 4) { priceStart = 600; priceEnd = 1000 }
    else if (that.data.selPriceId == 5) { priceStart = 1000; priceEnd = 2000 }
    wx.request({
      url: app.globalData.host + '/api/store/Search',
      data: {
        storeId: app.globalData.storeId,
        cateId: that.data.selCatId,
        word: that.data.Word,
        page: that.data.CurrentPage,
        pageSize: that.data.pageSize,
        priceStart: priceStart,
        priceEnd: priceEnd
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var newbs = [];
          var checkList = [];
          var rawData = res.data.Data;
          var products = rawData.ProductList;
          if (that.data.CurrentPage != 1) {
            var preGoods = that.data.goodsResult
            newbs = preGoods.concat(newbs);
          }
          for (var i = 0; i < products.length; i++) {
            var d = products[i];
            if (d.SKUGid == 0) {
              d.ShowImg = app.globalData.image800_800host + d.ShowImg;
              newbs.push(d);
            } else {
              if (!that.checkProduct(newbs, d.SKUGid)) {
                d.ShowImg = app.globalData.image800_800host + d.ShowImg;
                newbs.push(d);
              }
            }
          }
          that.setData({
            goodsResult: newbs,
            loadingMoreHidden: rawData.PageModel.HasNextPage
          });
        }
      }
    })
  },
  loadMore: function (e) {
    var that = this;
    if (!that.data.loadingMoreHidden) return;
    var currPage = that.data.CurrentPage;
    that.setData({
      CurrentPage: currPage + 1
    })
    that.searchGoods();
  },
  //sku产品去重
  checkProduct: function (products, text) {
    var state = false;  //默认不存在
    if (products.length > 0 & text != 0) {
      if (products.length > 0) {
        for (var i = 0; i < products.length; i++) {
          if (text == products[i].SKUGid) {
            state = true; //已经存在
            break;
          }
        }
      }
    }
    return state;
  },
  /** 点击类别外的区域，取消显示类别信息 */
  handleCoverTap: function (e) {
    this.setData({ "showSearch": false });
  },
  /** 重置标签页状态 */
  resetMenuTap: function (menu) {
    var readyData = { "isCategoryTap": false, "isBrandTap": false, "isPriceTap": false };
    this.setData(readyData);
  },
  handleCategoryTap: function (e) {
    console.log(e);
    if (this.data.showSearch == false) {
      this.setData({ "searchCategory": this.data.Categorys, "showSearch": true });
    } else if (this.data.showSearch == true) {
      this.setData({ "searchCategory": this.data.Categorys, "showSearch": false });
    }
    this.resetMenuTap();
    this.setData({ "isCategoryTap": true });
  },
  handlePriceTap: function (e) {
    this.setData({ "searchCategory": this.data.Prices, "showSearch": true });
    this.resetMenuTap();
    this.setData({ "isPriceTap": true });
  },
  handleBrandTap: function (e) {
    this.setData({ "searchCategory": this.data.Brands, "showSearch": true });
    this.resetMenuTap();
    this.setData({ "isBrandTap": true });
  },
  /** 点击某个子类型 */
  handleSearch: function (event) {
    var id = event.currentTarget.dataset.id;
    var name = event.currentTarget.dataset.name;
    var readyData = { "showSearch": false, CurrentPage: 1 };
    this.data.isCategoryTap && (readyData["selCatId"] = id);
    this.data.isCategoryTap && (readyData["selCatName"] = name);
    this.data.isBrandTap && (readyData["selBrandId"] = id);
    this.data.isBrandTap && (readyData["selBrandName"] = name);
    this.data.isPriceTap && (readyData["selPriceId"] = id);
    this.data.isPriceTap && (readyData["selPriceName"] = name);
    readyData["goodsResult"] = [];
    this.setData(readyData);
    this.searchGoods();
    this.resetMenuTap();
  },
  loadMore: function (e) {
    var that = this;
    if (!that.data.loadingMoreHidden) return;
    var currPage = that.data.CurrentPage;
    that.setData({
      CurrentPage: currPage + 1
    })
    that.searchGoods();
  },
  /** 点击完成按钮是触发 */
  handleConfirm: function (e) {
    this.data.Word = e.detail.value;
  },
  /** 搜索框失去焦点是触发 */
  handleBlur: function (e) {
    this.data.Word = e.detail.value;
  },
  /** 取消搜索 */
  handleCancel: function (e) {
    this.data.Word = '';
  },
  handleInput: function (e) {
    this.data.Word = e.detail.value;
  },
  handleSearchWord: function (e) {
    this.setData({
      CurrentPage: 1,
      selCatId: 0,
      selCatName: '',
      selBrandId: 0,
      selBrandName: '',
      selPriceId: 0,
      selPriceName: '',
      isCategoryTap: false,
      isBrandTap: false,
      isPriceTap: false,
      showSearch: false,
      searchCategory: [],//当前搜索类型
      goodsResult: [],
      loadingMoreHidden: false
    })
    this.searchGoods();
  },
  onPullDownRefresh: function () {
    var that = this;
    wx.showToast({
      title: '正在刷新',
      duration: 1500,
      icon: 'loading',
      success: function () {
        that.setData({ CurrentPage: 1 });
        that.searchGoods();
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var cardid = wx.getStorageSync("cardid");
      return {
        title: '',
        path: '/pages/classes-new/index?cardid=' + cardid + '&source=2',
        success: function (res) {
          wx.showModal({
            title: '提示',
            content: '转发成功',
            showCancel: false
          })
          utils.aiCardActionRecord(13);
        }
      }
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMore()
  },

  //showType = 2
  tapSearch: function (e) {
    wx.navigateTo({
      url: "/pages/classes/index"
    })
  },

  selectMenu: function (e) {
    var that = this
    var index = e.currentTarget.dataset.indexid
    var id = e.currentTarget.dataset.id
    var name = e.currentTarget.dataset.name
    var imgsrc = e.currentTarget.dataset.imgsrc
    that.setData({
      selectedMenuId: index,
      imgsrc: imgsrc,
      selectid: id,
      selectname: name,
      CurrentPage: 1,
      productArr: [],
      showProduct: true
    })
    that.searchGoods2(id, that.data.categoriesTwo)
  },
  addShopCar: function (e) {
    var pid = e.currentTarget.dataset.id
    var that = this;
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    }

    wx.request({
      url: app.globalData.host + '/api/cart/AddProduct',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: pid,
        buyCount: 1
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            shopNum: res.data.Data
          });
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  getClassTwoData: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/store/GetStoreClassList',
      data: {
        storeId: app.globalData.storeId
      },
      success: function (res) {
        var categories = [];
        var categoriesTwo = [];
        if (res.data.Code == 0) {
          var logoclassOne = app.globalData.image_logo_class + res.data.Data[0].Logo
          for (var i = 0; i < res.data.Data.length; i++) {
            var temp = res.data.Data[i];
            if (temp.ParentId == 0)//只展示一级类目
            {
              var c = {};
              c.parentid = temp.ParentId
              c.id = temp.StoreCid;
              c.name = temp.Name;
              c.Logo = app.globalData.image_logo_class + temp.Logo;
              categories.push(c);
            }
            if (temp.HasChild == 1 && temp.Layer == 1 || temp.Layer > 2) {
              continue;
            } else {
              if (temp.Layer == 2 || temp.HasChild == 0) {
                var h = {};
                h.id = temp.StoreCid;
                h.name = temp.Name;
                h.Layer = temp.Layer;//等级
                h.ParentId = temp.ParentId;//父级id，0是最大级
                h.Logo = app.globalData.image_logo_class + temp.Logo;//分类图片
                h.HasChild = temp.HasChild//是否有子类
                h.productArr = [];
                categoriesTwo.push(h);
              }
            }
          }
          that.setData({
            Categorys: categories,
            categoriesTwo: categoriesTwo,
            logoclassOne: logoclassOne,
            selectid: categories[0].id,
            selectname: categories[0].name,
          });
          that.searchGoods2(categories[0].id, categoriesTwo)
        }
      }
    })
  },
  searchGoods2: function (id, categories) {
    var that = this;
    let cateId = [];
    for (var j = 0; j < categories.length; j++) {
      if (id == categories[j].ParentId) {
        cateId.push({ id: categories[j].id, name: categories[j].name })
      }
    }
    if (cateId.length == 0) {
      cateId.push({ id: id, name: "" })
    }
    that.getProductList(cateId);
  },
  //获取商品列表
  getProductList: function (cateId) {
    var that = this;
    that.searchProduct({
      url: app.globalData.host + '/api/store/Search',//请求接口
      path: cateId//二级分类id数组
    });
  },
  //多次请求接口
  searchProduct: function (data) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.request({
      url: data.url,
      data: {
        storeId: app.globalData.storeId,
        cateId: data.path[i].id,
        word: "",
        page: that.data.CurrentPage,
        pageSize: 8,
        priceStart: 0,
        priceEnd: 0
      },
      success: (res) => {
        success++;
        if (res.data.Code == 0) {
          var list = [];
          var ProductList = res.data.Data.ProductList;
          for (var k = 0; k < ProductList.length; k++) {
            ProductList[k].ShowImg = app.globalData.image800_800host + ProductList[k].ShowImg
          }
          list.push({ id: data.path[i].id, title: data.path[i].name, HasNextPage: res.data.Data.PageModel.HasNextPage, arr: ProductList });
          if (i != 0) {
            var productArr = that.data.productArr
            list = productArr.concat(list)
          }
          if (that.data.CurrentPage != 1) {
            list = [];
            var productArr = that.data.productArr
            for (var j = 0; j < productArr.length; j++) {
              if (productArr[j].id == data.path[i].id) {
                list.push({ id: data.path[i].id, title: productArr[j].title, HasNextPage: res.data.Data.PageModel.HasNextPage, arr: productArr[j].arr.concat(ProductList) })
              } else {
                list.push({ id: productArr[j].id, title: productArr[j].title, HasNextPage: productArr[j].HasNextPage, arr: productArr[j].arr })
              }
            }
          }
          if (list[0].arr.length == 0) {
            that.setData({
              showProduct: false
            })
          }
          that.setData({
            productArr: list
          })
        }
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        i++;
        if (i == data.path.length) {  //当图片传完时，停止调用    
          wx.hideLoading();
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
        } else {//若图片还没有传完，则继续调用函数
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.searchProduct(data);
        }

      }
    });
  },

  //查看更多
  loadMore2: function (e) {
    var that = this;
    let id = e.currentTarget.dataset.cid
    let name = e.currentTarget.dataset.name
    let currPage = that.data.CurrentPage;
    that.setData({
      CurrentPage: currPage + 1
    })
    let cateId = [{ id: id, name: name }]
    that.getProductList(cateId);
  },
  
})